<?php
FLEA::loadClass('FLEA_Helper_Image');
class Api_Lib_Rsp_Image{

    function __construct() {
        $this->_model = FLEA::getSingleton('Model_Jichu_Image');

        //根域名
        $baseUrlstr = detect_uri_base();
        $this->serverUrl = substr($baseUrlstr, 0,strrpos(strtolower($baseUrlstr), 'api.php'));
    }

    //获取userid
    function uploadImg($params,& $service){
        //获取上传的图片
        $key = isset($_FILES['Images']) ? 'Images' : key($_FILES);
        $fileImage = $_FILES[$key];
        // dump($fileImage);exit;

        if(!$fileImage){
            $service->send_user_error('ERROR_DATA : Files_Image is null');
        }

        //上传文件的类型
        $uploadType = array('jpg','jpeg','png');
        $pathinfo = pathinfo($fileImage['name']);
        $extType = $pathinfo['extension'];
        // dump($pathinfo);exit;
        if(!in_array($extType , $uploadType)){
            $service->send_user_error('ERROR_DATA : Files_Image type is error');
        }
        //上传文件的最大值
        $max_size = 12 * 1024 * 1024; //12M
        if($fileImage['size'] > $max_size){
            $service->send_user_error('ERROR_DATA : Files_Image size > 12M');
        }

        //获取图片信息
        $size = getimagesize($fileImage['tmp_name']);
        $width  = $size[0];
        $height = $size[1];

        $pathRoot = 'upload/Images/';

        $rand = rand(10000, 99999);
        $randName = date('ymdHis') . $rand.'.'.$extType;
        $randNameSmall = date('ymdHis') . $rand.'.small.'.$extType;
        $imagePath = $pathRoot.$randName;
        $imagePathSmall = $pathRoot.$randNameSmall;


        //发现这个图片处理会导致图片变的比原来还大，所以直接使用上面的代码，移动到目录下
        if($width > 0 && $height > 0){
            //计算图片需要的内存，防止内存溢出
            $memoryLimit = ceil($width*$height/131072);
            if($memoryLimit > 128 && $memoryLimit <= 1024){
                 @ini_set('memory_limit', $memoryLimit.'M');
            }else if($memoryLimit > 1024){
                $service->send_user_error('ERROR_DATA : 图片分辨率过大');
            }
        }

        //缩略图
        FLEA::loadClass('FLEA_Helper_Image');
        $img = & FLEA_Helper_Image::createFromFile($fileImage['tmp_name'], $extType);
        //计算压缩比例
        $max = 1000;
        if($width > $height && $width > $max){
            $rate = $max / $width;
            $height2 = $height * $rate;
            $width2  = $max;
        }elseif($height > $width && $height > $max){
            $rate = $max / $height;
            $height2 = $max;
            $width2  = $width * $rate;
        }else{
            $height2 = $height;
            $width2  = $width;
        }

        $_m = $fileImage['size']/1024/1024;
        $level = $_m > 2 ? ($_m > 5 ? 80 : 90) : 100;
        $img->resampled($width2 , $height2);
        $img->saveAsJpeg($imagePathSmall , $level);

        move_uploaded_file($fileImage['tmp_name'] ,$imagePath);

        //保存到表里
        $arr = array(
            'path'      => $imagePath,
            'smallPath' => $imagePathSmall,
            'width'     => $width,
            'height'    => $height,
            'time'      => time(),
        );
        $id = $this->_model->save($arr);

        //测试工具控件返回值专用，不作为正式接口的使用！！！！！
        if($params['test'] == 'yes'){
            $_result = array('success' => true ,'imgPath'=>$this->serverUrl.$imagePath ,'imageId'=>$id ,'msg'=>'上传成功');
            echo json_encode($_result);exit;
        }
        //正式接口返回值
        return array('status' => true ,'imagePath'=>$this->serverUrl.$imagePath ,'imageId'=>$id);
    }

    //上传图片base64格式
    function uploadImageBase64($params,& $service){
        $fileImage = $params['Images'];
        if(!$fileImage){
            $service->send_user_error('ERROR_DATA : params Images is not found');
        }

        $path = 'upload/Images/';
        // dump($fileImage);
        //获取64位图片信息
        if( preg_match('/^(data:\s*image\/(\w+);base64,)/', $fileImage, $result) ){
            $type = strtolower($result[2]);
            $type == 'jpeg' && $type = 'jpg';
            $image = base64_decode(str_replace($result[1], '', $fileImage));
            // dump($result);
            $rand = rand(10000,99999);
            $name = date('ymdHis').$rand.'.'.$type;
            $nameSmall = date('ymdHis').$rand.'.small.'.$type;

            //把图片放入服务器目录中
            $imgPath = $path.$name;
            $imgPathSmall = $path.$nameSmall;
            $putSize = file_put_contents($imgPath ,$image);

            $info = getimagesize($fileImage);
            $width = $info[0]+0;
            $height = $info[1]+0;

            //处理缩略图
            //缩略图
            FLEA::loadClass('FLEA_Helper_Image');
            $img = & FLEA_Helper_Image::createFromFile($imgPath, $type);
            //计算压缩比例
            $max = 1000;
            if($width > $height && $width > $max){
                $rate = $max / $width;
                $height2 = $height * $rate;
                $width2  = $max;
            }elseif($height > $width && $height > $max){
                $rate = $max / $height;
                $height2 = $max;
                $width2  = $width * $rate;
            }else{
                $height2 = $height;
                $width2  = $width;
            }

            $img->resampled($width2 , $height2);
            $img->saveAsJpeg($imgPathSmall , 90);
        }

        //保存到表里
        $arr = array(
            'path'      => $imgPath,
            'smallPath' => $imgPathSmall,
            'width'     => $width,
            'height'    => $height,
            'time'      => time(),
        );
        // dump($arr);exit;

        $id = $this->_model->save($arr);


        return array('status' => true ,'imagePath'=>$this->serverUrl.$imgPath ,'imageId'=>$id);
    }
}
?>